
package rp.lee.weblog;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

import rp.lee.weblog.utils.KVContainer;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.iih5.netbox.annotation.Protocol;
import com.iih5.netbox.annotation.Request;
import com.iih5.netbox.message.Message;
import com.iih5.netbox.message.StringMessage;
import com.iih5.netbox.session.ISession;

@SuppressWarnings("rawtypes")
@Request
public class LogHandler {
	public static Map<String, KVContainer<InputStream, Process>> map = new ConcurrentHashMap<String, KVContainer<InputStream, Process>>();
	static Map<String, String> TYPE_FOR_PATH = new HashMap<String, String>();
	static {
		Properties properties = new Properties();
		
		try {
			properties.load(LogHandler.class.getResourceAsStream("web-log-types.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			File file = new File(System.getProperty("user.dir") + "/web-log-types.properties");
			if(!file.exists()) {
				System.out.println("没有jar包同级目录的web-log-types.properties配置");
			} else {
				properties.load(new FileInputStream(new File(System.getProperty("user.dir") + "/web-log-types.properties")));
			}
		} catch (IOException e) {
			System.out.println("没有jar包同级目录的web-log-types.properties配置");
		}
		
		for(Map.Entry entry : properties.entrySet()) {
			TYPE_FOR_PATH.put(entry.getKey().toString(), entry.getValue().toString());
		}
		
		for(Map.Entry entry : TYPE_FOR_PATH.entrySet()) {
			System.out.println("~===协议信息:" + entry.getKey() + "-" + entry.getValue());
		}
	}
	
	public static void clear(ISession session) {
		KVContainer<InputStream, Process> kv = null;
		if(map.containsKey(session.getId())) {
			kv = map.get(session.getId());
			map.containsKey(session.getId());
		}
		
		if(kv != null) {
			try {
				if (kv.getKey() != null)
					kv.getKey().close();
			} catch (Exception e) {
				e.printStackTrace();
			}

			try {
				if (kv.getValue() != null)
					kv.getValue().destroy();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	@Protocol(value = 1000)
	public void reqLogTypes(Message msg, ISession session) throws Exception {
		clear(session);
		
		StringMessage message = (StringMessage) msg;
		
		JsonElement jsonElement = new JsonParser().parse(message.getContent());
		if(!jsonElement.isJsonArray()) {
			throw new RuntimeException("JSON非法.");
		}
		JsonArray jsonArray = jsonElement.getAsJsonArray();
		StringBuffer buffer = new StringBuffer("tail ");
		
		for(JsonElement element : jsonArray) {
			String key = element.getAsString();
			if(TYPE_FOR_PATH.containsKey(key)) {
				buffer.append(" -f ").append(TYPE_FOR_PATH.get(key)).append(" ");
			}
		}
		
		Process process = Runtime.getRuntime().exec(buffer.toString());
		InputStream inputStream = process.getInputStream();
		// 一定要启动新的线程，防止InputStream阻塞处理WebSocket的线程
		TailLogThread thread = new TailLogThread(inputStream, session);
		thread.start();

		map.put(session.getId(), new KVContainer<InputStream, Process>(inputStream, process));
		StringMessage retMsg = new StringMessage((short)1000);
		retMsg.setContent("~========创建成功!<br>");
		session.send(retMsg);
	}
}
